using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace UdpDemo
{
    class UdpClient
    {
        public static async Task RunClient()
        {
            Console.Write("请输入要连接的UDP服务器端口(默认50789): ");
            string portInput = Console.ReadLine();
            int port = 50789; // 默认端口
            
            if (!string.IsNullOrEmpty(portInput) && int.TryParse(portInput, out int inputPort))
            {
                port = inputPort;
            }
            
            Console.WriteLine($"UDP客户端 - 发送数据到{port}端口");
            
            // 创建UDP客户端
            using (System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient())
            {
                try
                {
                    // 设置目标地址和端口
                    IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
                    
                    while (true)
                    {
                        Console.Write("请输入要发送的消息(输入'exit'退出): ");
                        string message = Console.ReadLine();
                        
                        if (message?.ToLower() == "exit")
                            break;
                        
                        // 将消息转换为字节数组
                        byte[] data = Encoding.UTF8.GetBytes(message ?? string.Empty);
                        
                        // 发送数据
                        await client.SendAsync(data, data.Length, serverEndPoint);
                        Console.WriteLine($"已发送: {message}");
                        
                        // 显示HEX格式
                        string hexString = BitConverter.ToString(data).Replace("-", " ");
                        Console.WriteLine($"HEX格式: {hexString}");
                        Console.WriteLine();
                        
                        // 等待一小段时间
                        await Task.Delay(100);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"发送数据时出错: {ex.Message}");
                }
            }
        }
    }
}